package com.wish.g04.renting.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.wish.g04.base.dto.SfContractDTO;
import com.wish.g04.base.entity.CwPaymentPlan;
import com.wish.g04.base.entity.MAttachment;
import com.wish.g04.base.entity.SfContract;
import com.wish.g04.base.entity.SfTermination;
import com.wish.g04.base.service.IMAttachmentService;
import com.wish.g04.base.service.ISfTerminationService;
import com.wish.g04.common.core.utils.bean.BeanUtils;
import com.wish.g04.common.core.web.controller.BaseController;
import com.wish.g04.common.core.web.domain.AjaxResult;
import com.wish.g04.common.core.web.page.TableDataInfo;
import com.wish.g04.common.security.utils.SecurityUtils;
import com.wish.g04.renting.dto.PaymentDTO;
import com.wish.g04.renting.dto.SfTerminationDTO;
import com.wish.g04.renting.service.TSfContractService;
import com.wish.g04.renting.service.TSfTerminationService;
import com.wish.g04.renting.vo.SfContractDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wish.g04.common.log.annotation.Log;
import com.wish.g04.common.log.enums.BusinessType;
import com.wish.g04.common.security.annotation.PreAuthorize;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.annotation.Resource;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2022-06-04
 */
@RestController
@RequestMapping("/termination")
public class SfTerminationController extends BaseController
{
    @Autowired
    private TSfTerminationService iSfTerminationService;

    @Autowired
    private TSfContractService tSfContractService;

    @Autowired
    ISfTerminationService sfTerminationService;

    @Autowired
    IMAttachmentService imAttachmentService;

    /**
     * 解约协议获取收房合同列表
     * @param sfContractDTO
     * @return
     */
    @PreAuthorize(hasPermi = "system:contract:list")
    @GetMapping("/searchContractList")
    public TableDataInfo list(SfContractDTO sfContractDTO)
    {
        startPage();
        TableDataInfo getlist = tSfContractService.getlist(sfContractDTO);
        return getlist;
    }


    @GetMapping(value = "/searchContractById")
    public AjaxResult searchSfAllById(SfContractDTO sfContractDTO) {
        //查询收房合同信息
        SfContract tSfContract = iSfTerminationService.selectSearchById(sfContractDTO.getSfContractId());
        SfContractDetailVO responseDetailSfContractDto = new SfContractDetailVO();
        BeanUtils.copyProperties(tSfContract, responseDetailSfContractDto);
        //查询付款计划
        List<CwPaymentPlan> list = iSfTerminationService.selectcwPaymentPlanList(sfContractDTO.getSfContractId(), 1);
        ArrayList<PaymentDTO> paymentList = new ArrayList<PaymentDTO>();
        PaymentDTO paymentDto = null;
        if (list != null && list.size() > 0) {
            for (CwPaymentPlan record : list) {
                paymentDto = new PaymentDTO();
                BeanUtils.copyProperties(record, paymentDto);
                paymentDto.setPaymentId(record.getId());
                paymentList.add(paymentDto);
            }
        }
        // 续约时，结束时间加1
        Calendar c = Calendar.getInstance();
        Date leaseEndTime = responseDetailSfContractDto.getLeaseEndTime();
        c.setTime(leaseEndTime);
        c.add(Calendar.DATE, 1);
        leaseEndTime = c.getTime();
        responseDetailSfContractDto.setLeaseEndTime(leaseEndTime);
        responseDetailSfContractDto.setPaymentList(paymentList);
        BigDecimal money = new BigDecimal("0.00");
        Date date = new Date();
        //算出日租金
        BigDecimal dayMonthRent = responseDetailSfContractDto.getMonthRent().divide(new BigDecimal(30), 2);
        //多少日
        Long day = new Long(0);
        for (PaymentDTO receiptDto : responseDetailSfContractDto.getPaymentList()) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("收款计划id=" + receiptDto.getPaymentId() + ",账期开始日=" + dateFormat.format(receiptDto.getPaymentDaysBegin()) + ",账期截止日=" + dateFormat.format(receiptDto.getPaymentDaysEnd()) + ",第几期（房租收款的时候）=" + receiptDto.getPayNumber() + ",收款状态(1:未收款 2：已收款 3：已中止)=" + receiptDto.getPayState());
            //判断收款状态是否为已收款
            if (receiptDto.getPayState() == 2) {
                //判断费用类型(3：租金)   枚举：BusinessCostTypesEnum
                if (receiptDto.getItemType() == 80) {
                    //判断该租金账期开始时间小于当前时间和结束时间大于当前时间
                    if (date.before(receiptDto.getPaymentDaysEnd()) || date.after(receiptDto.getPaymentDaysBegin())) {
                        //用账期结束时间减去当前时间，算出多少天
                        day = (receiptDto.getPaymentDaysEnd().getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
                    }
                }
                //判断费用类型(2：押金)
                else if (receiptDto.getItemType() == 81) {
                    money = money.add(receiptDto.getPaymentAmount());
                    System.out.println("押金已付款");
                } else {
                    responseDetailSfContractDto.setDepositMoney(new BigDecimal(0));
                }
            } else {
                responseDetailSfContractDto.setDepositMoney(new BigDecimal(0));
            }
        }
        responseDetailSfContractDto.setDepositMoney(money);
        responseDetailSfContractDto.setAltogetherRent(dayMonthRent.multiply(new BigDecimal(day)));
        return AjaxResult.success(responseDetailSfContractDto);
    }

    @Resource
    private JavaMailSenderImpl javaMailSenderimpl;
    /**
     * @Date 2022/3/30 14:44
     * @deprecated 保存解约信息
     **/
    @PostMapping(value = "/addTermination")
    public AjaxResult addTermination(@RequestBody SfTerminationDTO sfTerminationDTO) throws MessagingException {
        System.out.println("解约信息:" + sfTerminationDTO.toString());
        //修改合同状态为解约状态
        iSfTerminationService.UpdateState(sfTerminationDTO.getSfContractId());
        //获取用户信息ID
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        //保存解约信息
        SfTermination sfTermination = new SfTermination();
        BeanUtils.copyProperties(sfTerminationDTO,sfTermination);
        sfTermination.setCreateUserid(userId);
        sfTermination.setInputUserId(userId);
        sfTermination.setInputUserName(username);
        sfTermination.setInputDate(new Date());
        sfTermination.setCreateTime(new Date());
        sfTermination.setUpdateUserid(userId);
        sfTermination.setUpdateTime(new Date());
        System.out.println("解约信息:"+sfTermination);
        sfTerminationService.save(sfTermination);
        //保存附件信息
        for (String contractPhoto : sfTerminationDTO.getContractPhotos()) {
            MAttachment tmAttachment = new MAttachment();
            tmAttachment.setRelationId(sfTermination.getId());
            tmAttachment.setRelationType(11);
            tmAttachment.setAttachmentType(7);
            tmAttachment.setUrl(contractPhoto);
            tmAttachment.setCreateUserid(userId);
            tmAttachment.setCreateTime(LocalDateTime.now());
            imAttachmentService.save(tmAttachment);
        }
        for (String contractPhoto : sfTerminationDTO.getPropertyDeliverys()) {
            MAttachment tmAttachment = new MAttachment();
            tmAttachment.setRelationId(sfTermination.getId());
            tmAttachment.setRelationType(11);
            tmAttachment.setAttachmentType(10);
            tmAttachment.setUrl(contractPhoto);
            tmAttachment.setCreateUserid(userId);
            tmAttachment.setCreateTime(LocalDateTime.now());
            imAttachmentService.save(tmAttachment);
        }
        for (String contractPhoto : sfTerminationDTO.getOtherPhotos()) {
            MAttachment tmAttachment = new MAttachment();
            tmAttachment.setRelationId(sfTermination.getId());
            tmAttachment.setRelationType(11);
            tmAttachment.setAttachmentType(99);
            tmAttachment.setUrl(contractPhoto);
            tmAttachment.setCreateUserid(userId);
            tmAttachment.setCreateTime(LocalDateTime.now());
            imAttachmentService.save(tmAttachment);
        }

        //邮箱发送
        MimeMessage mimeMessage = javaMailSenderimpl.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo("3406185119@qq.com");
        helper.setText("<html><body><font color='red' size='30'>" + "编号为"+sfTerminationDTO.getSfContractNo()+"解约成功" + "</font>" +
                "</body></html>", true);
        helper.setFrom("3406185119@qq.com");
        helper.setSubject("你以被该公司解约");
        helper.setSentDate(new Date());
        helper.setReplyTo("我不要");
        javaMailSenderimpl.send(mimeMessage);

        return AjaxResult.success();
    }
    /**
     * 查询【请填写功能名称】列表
     */
//    @PreAuthorize(hasPermi = "system:termination:list")
//    @GetMapping("/list")
//    public TableDataInfo list(TSfTermination tSfTermination)
//    {
//        startPage();
//        List<TSfTermination> list = tSfTerminationService.selectTSfTerminationList(tSfTermination);
//        return getDataTable(list);
//    }



    /**
     * 新增【请填写功能名称】
     */
//    @PreAuthorize(hasPermi = "system:termination:add")
//    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody TSfTermination tSfTermination)
//    {
//        return toAjax(tSfTerminationService.insertTSfTermination(tSfTermination));
//    }

    /**
     * 修改【请填写功能名称】
     */
//    @PreAuthorize(hasPermi = "system:termination:edit")
//    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody TSfTermination tSfTermination)
//    {
//        return toAjax(tSfTerminationService.updateTSfTermination(tSfTermination));
//    }

}
